<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书购物车系统</title>
    <style>
        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            flex: 1;
        }
        .header {
            background: linear-gradient(135deg, #1e5799 0%,#207cca 51%,#2989d8 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
            display: flex;
            align-items: center;
        }
        .logo i {
            margin-right: 10px;
            font-size: 28px;
        }
        .nav {
            display: flex;
        }
        .nav-item {
            margin-left: 30px;
            cursor: pointer;
            font-size: 16px;
            transition: color 0.3s;
            padding: 5px 10px;
            border-radius: 4px;
            position: relative;
        }
        .nav-item:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .cart-count {
            position: absolute;
            top: -8px;
            right: -8px;
            background-color: #e74c3c;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .page-title {
            font-size: 24px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #ebeef5;
            color: #1e5799;
        }
        .footer {
            text-align: center;
            padding: 30px 0;
            color: #909399;
            font-size: 14px;
            margin-top: 50px;
            border-top: 1px solid #ebeef5;
            background: white;
        }
        .loading {
            text-align: center;
            padding: 50px 0;
            font-size: 16px;
            color: #909399;
        }
        .empty {
            text-align: center;
            padding: 50px 0;
            font-size: 16px;
            color: #909399;
        }
        .empty i {
            font-size: 50px;
            color: #c0c4cc;
            margin-bottom: 20px;
        }

        /* 图书列表页特定样式 */
        .book-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .book-card {
            background: white;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            cursor: pointer;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .book-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.2);
        }
        .book-image {
            width: 100%;
            height: 200px;
            background-color: #f0f2f5;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        .book-image img {
            max-width: 100%;
            max-height: 100%;
            object-fit: cover;
        }
        .book-info {
            padding: 20px;
            flex-grow: 1;
        }
        .book-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #303133;
            height: 50px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        .book-price {
            color: #e74c3c;
            font-size: 20px;
            font-weight: bold;
            margin: 10px 0;
        }
        .book-desc {
            color: #606266;
            font-size: 14px;
            height: 63px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }
        .book-footer {
            padding: 10px 20px;
            background-color: #f5f7fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #909399;
        }
        .pagination {
            margin-top: 30px;
            display: flex;
            justify-content: center;
        }

        /* 图书详情页特定样式 */
        .back-button {
            margin-top: 30px;
            text-align: center;
        }
        .detail-container {
            background: white;
            border-radius: 6px;
            padding: 30px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .detail-header {
            display: flex;
            margin-bottom: 30px;
        }
        .detail-image {
            width: 300px;
            height: 400px;
            background-color: #f5f7fa;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 30px;
            border-radius: 4px;
            overflow: hidden;
        }
        .detail-image img {
            max-width: 100%;
            max-height: 100%;
        }
        .detail-info {
            flex-grow: 1;
        }
        .detail-title {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #1e5799;
        }
        .detail-price {
            color: #e74c3c;
            font-size: 26px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        .detail-meta {
            margin-bottom: 25px;
        }
        .detail-meta-item {
            margin-bottom: 8px;
            font-size: 16px;
            color: #606266;
        }
        .detail-meta-label {
            display: inline-block;
            width: 120px;
            color: #909399;
        }
        .detail-desc {
            line-height: 1.8;
            color: #606266;
            font-size: 16px;
            margin-bottom: 30px;
        }
        .cart-actions {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .quantity-selector {
            margin-right: 20px;
        }

        /* 购物车页特定样式 */
        .cart-container {
            background: white;
            border-radius: 6px;
            padding: 30px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .cart-item {
            display: flex;
            padding: 20px 0;
            border-bottom: 1px solid #ebeef5;
        }
        .cart-item-image {
            width: 100px;
            height: 150px;
            background-color: #f5f7fa;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 20px;
            border-radius: 4px;
            overflow: hidden;
        }
        .cart-item-image img {
            max-width: 100%;
            max-height: 100%;
        }
        .cart-item-info {
            flex-grow: 1;
        }
        .cart-item-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #303133;
        }
        .cart-item-price {
            color: #e74c3c;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .cart-item-meta {
            color: #909399;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .cart-item-actions {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
        .cart-summary {
            margin-top: 30px;
            padding: 20px;
            background-color: #f5f7fa;
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .cart-total {
            font-size: 18px;
            font-weight: bold;
        }
        .total-price {
            color: #e74c3c;
            font-size: 24px;
        }
        .cart-buttons {
            display: flex;
            gap: 15px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .detail-header {
                flex-direction: column;
            }
            .detail-image {
                width: 100%;
                margin-right: 0;
                margin-bottom: 20px;
            }
            .book-list {
                grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            }
            .cart-item {
                flex-direction: column;
            }
            .cart-item-image {
                width: 100%;
                height: 200px;
                margin-right: 0;
                margin-bottom: 15px;
            }
            .cart-summary {
                flex-direction: column;
                gap: 20px;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
<!-- 顶部导航 - 所有页面共享 -->
<div class="header">
    <div class="header-content">
        <div class="logo">
            <i class="el-icon-reading"></i>
            图书购物车系统
        </div>
        <div class="nav">
            <a href="book_list.html" class="nav-item">图书列表</a>
            <a href="cart.html" class="nav-item">
                购物车
                <span id="cart-count" class="cart-count">0</span>
            </a>
        </div>
    </div>
</div>

<!-- 页面内容区域 -->
<div class="container">
    <!-- 图书列表页 -->
    <div id="book-list-page" class="page-content">
        <h1 class="page-title">图书列表</h1>

        <div class="book-list">
            <!-- 图书卡片将通过JS动态生成 -->
        </div>

        <div id="empty-list" class="empty" style="display: none;">
            <i class="el-icon-notebook-2"></i>
            <p>暂无图书数据</p>
        </div>

        <div class="pagination">
            <div id="pagination-controls"></div>
        </div>
    </div>

    <!-- 图书详情页 -->
    <div id="book-detail-page" class="page-content" style="display: none;">
        <div class="back-button">
            <a href="book_list.html" class="el-button el-button--primary">
                <i class="el-icon-arrow-left"></i> 返回列表
            </a>
        </div>

        <h1 class="page-title">图书详情</h1>

        <div id="book-detail-container" class="detail-container" style="display: none;">
            <!-- 详情内容将通过JS动态生成 -->
        </div>

        <div id="detail-loading" class="loading">
            <i class="el-icon-loading"></i>
            <p>正在加载图书详情...</p>
        </div>
    </div>

    <!-- 购物车页 -->
    <div id="cart-page" class="page-content" style="display: none;">
        <div class="back-button">
            <a href="book_list.html" class="el-button el-button--primary">
                <i class="el-icon-arrow-left"></i> 返回列表
            </a>
        </div>

        <h1 class="page-title">我的购物车</h1>

        <div id="cart-container" class="cart-container" style="display: none;">
            <!-- 购物车内容将通过JS动态生成 -->
        </div>

        <div id="empty-cart" class="empty">
            <i class="el-icon-shopping-cart-2"></i>
            <p>购物车空空如也</p>
            <a href="book_list.html" class="el-button el-button--primary" style="margin-top: 20px;">去挑选图书</a>
        </div>
    </div>
</div>

<!-- 页脚 - 所有页面共享 -->
<div class="footer">
    © 2023 图书购物车系统 | 前端使用HTML+CSS+JavaScript实现
</div>

<!-- 引入必要的库 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    // 页面路由控制
    function showPage(pageId) {
        // 隐藏所有页面
        document.querySelectorAll('.page-content').forEach(page => {
            page.style.display = 'none';
        });

        // 显示请求的页面
        document.getElementById(pageId).style.display = 'block';
    }

    // 根据当前URL决定显示哪个页面
    function initPage() {
        const path = window.location.pathname;
        const page = path.substring(path.lastIndexOf('/') + 1);

        if (page === 'book_detail.html') {
            showPage('book-detail-page');
            const bookId = new URLSearchParams(window.location.search).get('id');
            if (bookId) {
                loadBookDetail(bookId);
            }
        } else if (page === 'cart.html') {
            showPage('cart-page');
            loadCart();
        } else {
            showPage('book-list-page');
            loadBooks();
        }

        // 更新购物车数量
        updateCartCount();
    }

    // 加载图书列表
    async function loadBooks() {
        document.getElementById('empty-list').style.display = 'none';

        try {
            const response = await axios.get('http://localhost:8081/books/queryBooks');
            const books = response.data;

            if (books.length === 0) {
                document.getElementById('empty-list').style.display = 'block';
                return;
            }

            const bookList = document.querySelector('.book-list');
            bookList.innerHTML = '';

            books.forEach(book => {
                const bookCard = document.createElement('div');
                bookCard.className = 'book-card';
                bookCard.innerHTML = `
                        <div class="book-image">
                            <img src="${getBookImage(book.bookImage)}" alt="${book.bookName}">
                        </div>
                        <div class="book-info">
                            <div class="book-title">${book.bookName}</div>
                            <div class="book-price">¥${book.bookPrice.toFixed(2)}</div>
                            <div class="book-desc">${book.bookDesc}</div>
                        </div>
                        <div class="book-footer">
                            <div>ID: ${book.bookId}</div>
                            <div>${book.bookIsDisplay === -1 ? '未上架' : '已上架'}</div>
                        </div>
                    `;

                // 点击跳转到详情页
                bookCard.addEventListener('click', () => {
                    window.location.href = `book_detail.html?id=${book.bookId}`;
                });

                bookList.appendChild(bookCard);
            });

            // 初始化分页
            initPagination(books.length);

        } catch (error) {
            console.error('获取图书列表失败:', error);
            document.getElementById('empty-list').style.display = 'block';
            document.getElementById('empty-list').innerHTML = `
                    <i class="el-icon-warning"></i>
                    <p>加载图书数据失败，请稍后重试</p>
                `;
        }
    }

    // 初始化分页
    function initPagination(totalItems) {
        const pagination = document.getElementById('pagination-controls');
        pagination.innerHTML = '';

        // 实际项目中应实现完整分页逻辑
        // 这里简化为显示总数量
        const info = document.createElement('div');
        info.className = 'pagination-info';
        info.textContent = `共 ${totalItems} 本图书`;
        pagination.appendChild(info);
    }

    // 加载图书详情
    async function loadBookDetail(bookId) {
        document.getElementById('book-detail-container').style.display = 'none';
        document.getElementById('detail-loading').style.display = 'block';

        try {
            const response = await axios.get(`http://localhost:8081/books/findBookById/${bookId}`);
            const book = response.data;

            const detailContainer = document.getElementById('book-detail-container');
            detailContainer.innerHTML = `
                    <div class="detail-header">
                        <div class="detail-image">
                            <img src="${getBookImage(book.bookImage)}" alt="${book.bookName}">
                        </div>
                        <div class="detail-info">
                            <h1 class="detail-title">${book.bookName}</h1>
                            <div class="detail-price">¥${book.bookPrice.toFixed(2)}</div>

                            <div class="detail-meta">
                                <div class="detail-meta-item">
                                    <span class="detail-meta-label">图书ID：</span>
                                    ${book.bookId}
                                </div>
                                <div class="detail-meta-item">
                                    <span class="detail-meta-label">上架状态：</span>
                                    <span class="status-tag ${book.bookIsDisplay === -1 ? 'danger' : 'success'}">
                                        ${book.bookIsDisplay === -1 ? '未上架' : '已上架'}
                                    </span>
                                </div>
                                <div class="detail-meta-item">
                                    <span class="detail-meta-label">创建时间：</span>
                                    ${book.createTime || '暂无信息'}
                                </div>
                                <div class="detail-meta-item">
                                    <span class="detail-meta-label">更新时间：</span>
                                    ${book.updateTime || '暂无信息'}
                                </div>
                                <div class="detail-meta-item">
                                    <span class="detail-meta-label">删除状态：</span>
                                    <span class="status-tag ${book.isDeleted === 0 ? 'success' : 'danger'}">
                                        ${book.isDeleted === 0 ? '未删除' : '已删除'}
                                    </span>
                                </div>
                            </div>

                            <div class="detail-desc">
                                ${book.bookDesc}
                            </div>

                            <div class="cart-actions">
                                <div class="quantity-selector">
                                    <input type="number" id="quantity" min="1" max="10" value="1" class="quantity-input">
                                </div>
                                <button id="add-to-cart" class="add-to-cart-btn">
                                    <i class="el-icon-shopping-cart-full"></i> 加入购物车
                                </button>
                            </div>
                        </div>
                    </div>
                `;

            // 添加加入购物车事件
            document.getElementById('add-to-cart').addEventListener('click', () => {
                const quantity = parseInt(document.getElementById('quantity').value) || 1;
                addToCart(book, quantity);
            });

            document.getElementById('detail-loading').style.display = 'none';
            detailContainer.style.display = 'block';

        } catch (error) {
            console.error('获取图书详情失败:', error);
            document.getElementById('detail-loading').innerHTML = `
                    <i class="el-icon-warning"></i>
                    <p>加载图书详情失败，请稍后重试</p>
                    <a href="book_list.html" class="el-button el-button--primary" style="margin-top: 20px;">返回图书列表</a>
                `;
        }
    }

    // 加载购物车
    async function loadCart() {
        document.getElementById('cart-container').style.display = 'none';
        document.getElementById('empty-cart').style.display = 'none';

        try {
            // 假设用户ID为93
            const userId = "93";
            const response = await axios.get(`http://localhost:8081/car/getCarByUser/${userId}`);
            const cartItems = response.data;

            if (cartItems.length === 0) {
                document.getElementById('empty-cart').style.display = 'block';
                return;
            }

            const cartContainer = document.getElementById('cart-container');
            cartContainer.innerHTML = '';

            // 获取图书信息（实际项目中可能需要单独的API）
            const booksResponse = await axios.get('http://localhost:8081/books/queryBooks');
            const books = booksResponse.data;

            let totalPrice = 0;

            cartItems.forEach(item => {
                const book = books.find(b => b.bookId === item.bookId);
                if (!book) return;

                const itemPrice = book.bookPrice * item.carCount;
                totalPrice += itemPrice;

                const cartItem = document.createElement('div');
                cartItem.className = 'cart-item';
                cartItem.innerHTML = `
                        <div class="cart-item-image">
                            <img src="${getBookImage(book.bookImage)}" alt="${book.bookName}">
                        </div>
                        <div class="cart-item-info">
                            <div class="cart-item-title">${book.bookName}</div>
                            <div class="cart-item-price">¥${itemPrice.toFixed(2)}</div>
                            <div class="cart-item-meta">
                                <div>单价: ¥${book.bookPrice.toFixed(2)}</div>
                                <div>数量: ${item.carCount}</div>
                                <div>添加时间: ${formatDate(item.createTime) || '未知'}</div>
                            </div>
                            <div class="cart-item-actions">
                                <button class="remove-btn" data-id="${item.carId}">
                                    <i class="el-icon-delete"></i> 删除
                                </button>
                            </div>
                        </div>
                    `;

                cartContainer.appendChild(cartItem);
            });

            // 添加总结和操作按钮
            const summary = document.createElement('div');
            summary.className = 'cart-summary';
            summary.innerHTML = `
                    <div class="cart-total">
                        总计: <span class="total-price">¥${totalPrice.toFixed(2)}</span>
                    </div>
                    <div class="cart-buttons">
                        <button class="continue-btn">继续购物</button>
                        <button class="checkout-btn">结算订单</button>
                    </div>
                `;

            cartContainer.appendChild(summary);

            // 添加事件监听器
            document.querySelectorAll('.remove-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const carId = btn.getAttribute('data-id');
                    removeCartItem(carId);
                });
            });

            document.querySelector('.continue-btn').addEventListener('click', () => {
                window.location.href = 'book_list.html';
            });

            document.querySelector('.checkout-btn').addEventListener('click', checkout);

            cartContainer.style.display = 'block';

        } catch (error) {
            console.error('获取购物车数据失败:', error);
            document.getElementById('empty-cart').style.display = 'block';
            document.getElementById('empty-cart').innerHTML = `
                    <i class="el-icon-warning"></i>
                    <p>加载购物车数据失败，请稍后重试</p>
                    <a href="book_list.html" class="el-button el-button--primary" style="margin-top: 20px;">返回图书列表</a>
                `;
        }
    }

    // 添加到购物车
    async function addToCart(book, quantity) {
        try {
            const cartItem = {
                carId: "",
                bookId: book.bookId,
                carCount: quantity,
                userId: "93", // 假设当前用户ID为93
                createTime: "",
                updateTime: "",
                isDeleted: ""
            };

            await axios.post('http://localhost:8081/car/addCar', cartItem);

            alert(`已添加 ${quantity} 本《${book.bookName}》到购物车`);
            updateCartCount();

        } catch (error) {
            console.error('添加到购物车失败:', error);
            alert('添加到购物车失败，请稍后重试');
        }
    }

    // 从购物车中删除商品
    async function removeCartItem(carId) {
        if (!confirm('确定要删除该商品吗?')) return;

        try {
            // 实际项目中这里应该调用删除接口
            // 这里模拟删除操作
            alert('商品已从购物车移除');
            await loadCart(); // 重新加载购物车
            updateCartCount();

        } catch (error) {
            console.error('删除购物车商品失败:', error);
            alert('删除商品失败，请稍后重试');
        }
    }

    // 结算购物车
    function checkout() {
        const totalPrice = document.querySelector('.total-price').textContent;
        if (confirm(`确定要结算吗? 总金额: ${totalPrice}`)) {
            alert('结算成功，订单已生成');
            // 实际项目中这里应该调用结算接口
            window.location.href = 'book_list.html';
        }
    }

    // 更新购物车数量
    async function updateCartCount() {
        try {
            const userId = "93";
            const response = await axios.get(`http://localhost:8081/car/getCarByUser/${userId}`);
            const cartItems = response.data;

            const totalCount = cartItems.reduce((sum, item) => sum + item.carCount, 0);
            document.getElementById('cart-count').textContent = totalCount;

        } catch (error) {
            console.error('更新购物车数量失败:', error);
        }
    }

    // 获取图书图片
    function getBookImage(imageName) {
        return imageName ? `https://via.placeholder.com/200x280?text=Book+Cover` : 'https://via.placeholder.com/200x280?text=No+Image';
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', initPage);
</script>
</body>
</html>